package com.ape9527.bot.services;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ape9527.bot.core.Const;
import com.ape9527.bot.utils.http.HttpUtil;
import com.ape9527.bot.utils.openai.OpenAiUtil;
import com.ape9527.bot.utils.openai.model.ChatMessage;
import com.ape9527.bot.utils.openai.model.ChatResponse;
import com.ape9527.bot.vo.Message;
import com.ape9527.bot.vo.SendMsgVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author YuanShuai[apeblog@163.com]
 */
@Service
@Slf4j
public class BotServices {

    private final OpenAiUtil openAiUtil;

    public BotServices(OpenAiUtil openAiUtil) {
        this.openAiUtil = openAiUtil;
    }

    public void parsePrivateMessage(JSONObject msg) {
        log.info("<<<<<<<<<<收到私聊消息>>>>>>>>>>");
        log.info("消息类型: {}", parseSubType(msg.getString("sub_type")));
        log.info("消息ID: {}", msg.getLong("message_id"));
        log.info("发送者QQ号: {}", msg.getLong("user_id"));
        log.info("原始消息内容: {}", msg.getString("raw_message"));
        List<ChatMessage> chatMessages = new ArrayList<>();
        chatMessages.add(new ChatMessage("user", msg.getString("raw_message")));
        ChatResponse chatCompletion = openAiUtil.createChatCompletion(chatMessages);
        String content = chatCompletion.getChoices().get(0).getMessage().getContent();
        String messageId = sendPrivateMessage(msg.getLong("user_id"), content);
        log.info("new message id is {}", messageId);
        log.info("<<<<<<<<<<处理完成>>>>>>>>>>");
    }

    private String sendPrivateMessage(Long userId, String content) {
        JSONObject param  = new JSONObject();
        param.put("message_type", "private");
        param.put("user_id", userId);
        param.put("message",content);
        return HttpUtil.sendPost(Const.SEND_MSG, param.toString(), null, null);
    }

    public void parseGroupMessage(JSONObject msg) {
        log.info("<<<<<<<<<<收到群聊消息>>>>>>>>>>");
        log.info("消息类型: {}", parseSubType(msg.getString("sub_type")));
        log.info("消息ID: {}", msg.getLong("message_id"));
        log.info("群号: {}", msg.getLong("group_id"));
        log.info("发送者QQ号: {}", msg.getLong("user_id"));
        log.info("原始消息内容: {}", msg.getString("raw_message"));
        String message = msg.getString("message");
        // 解析CQ格式消息
        JSONObject cqMessage = parseCQMessage(message);
        JSONArray ats = cqMessage.getJSONArray("ats");
        // 获取当前登陆人信息
        String loginUserId = getLoginId();
        // 判断at中是否有当前用户
        if(ats.contains(loginUserId)){
            // 获取消息文本
            String content = cqMessage.getString("content");
            // 请求AI获取回复
            String resContent;
            try{
                List<ChatMessage> chatMessages = new ArrayList<>();
                chatMessages.add(new ChatMessage("user", content));
                ChatResponse chatCompletion = openAiUtil.createChatCompletion(chatMessages);
                resContent = chatCompletion.getChoices().get(0).getMessage().getContent();
            }catch (Exception e){
                resContent = "提问太快了，等会再问吧～";
                e.printStackTrace();
            }

            // 构建消息
            String resMsg = "[CQ:reply,id=" + msg.getLong("message_id") + "][CQ:at,qq=" + msg.getLong("user_id") + "] " +
                    "[CQ:at,qq=" + msg.getLong("user_id") + "] " + resContent;
            String messageId = sendGroupMessage(msg.getLong("group_id"), resMsg);
            log.info("new message id is {}", messageId);
        }
        log.info("<<<<<<<<<<处理完成>>>>>>>>>>");
    }

    private String sendGroupMessage(Long groupId, String msg) {
        JSONObject param  = new JSONObject();
        param.put("message_type", "group");
        param.put("group_id", groupId);
        param.put("message",msg);
        return HttpUtil.sendPost(Const.SEND_MSG, param.toString(), null, null);
    }


    private JSONObject parseCQMessage(String message) {
        JSONArray ats = new JSONArray();
        String messageText = null;
        while (true){
            try {
                int leftIndex = message.indexOf("[");
                int rightIndex = message.indexOf("]");
                if(leftIndex != -1 && rightIndex != -1){
                    String cq = message.substring(leftIndex, rightIndex + 1);
                    message = message.substring(rightIndex + 1);
                    String cqType = cq.substring(4, 6);
                    if("at".equals(cqType)){
                        String qq = cq.substring(10,cq.length()-1);
                        ats.add(qq);
                    }
                }else{
                    messageText = message.trim();
                    break;
                }
            }catch (Exception e){
                if(e instanceof StringIndexOutOfBoundsException){
                    messageText = message.trim();
                    break;
                }
                e.printStackTrace();
            }
        }
        JSONObject res = new JSONObject();
        res.put("ats", ats);
        res.put("content", messageText);
        return res;
    }

    private String parseSubType(String subType) {
        switch (subType){
            case "friend": return "好友";
            case "normal": return "群聊";
            case "anonymous": return "匿名";
            case "group_self": return "群中自身发送";
            case "group": return "群临时会话";
            case "notice": return "系统提示";
            default: return "未知";
        }
    }

    private String getLoginId(){
        String s = HttpUtil.sendGet(Const.LOGIN_INFO, null, null, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        return jsonObject.getJSONObject("data").getString("user_id");
    }
}
